<template>
  <v-chart :option="gaugeOption" :style="chartStyle" />
</template>

<script lang="ts">
import { defineComponent, computed, watch } from 'vue';
import { GaugeChart } from 'echarts/charts';
import { TooltipComponent, GridComponent } from 'echarts/components';
import { CanvasRenderer } from 'echarts/renderers';
import { use } from 'echarts/core';
import VChart from 'vue-echarts';

use([GaugeChart, TooltipComponent, GridComponent, CanvasRenderer]);

export default defineComponent({
  name: 'Gauge',
  components: {
    VChart,
  },
  props: {
    title: {
      type: String,
      required: true,
    },
    value: {
      type: Number,
      required: true,
    },
    unit: {
      type: String,
      default: '',
    },
  },
  setup(props) {
    const chartStyle = {
      height: '100%',
      width: '100%',
    };

    // 渐变色配置
    const gradient = {
      type: 'linear',
      x: 0,
      y: 0,
      x2: 1,
      y2: 1,
      colorStops: [
        { offset: 0, color: '#84fab0' }, // 起始颜色
        { offset: 1, color: '#8fd3f4' }, // 结束颜色
      ],
    };

    // 使用计算属性来确保 chartOption 更新
    const gaugeOption = computed(() => ({
      grid: {
        top: "0px",
        left: "0px",
        right: "0px",
        bottom: "0px"
      },
      series: [
        {
          type: 'gauge',
          data: [{ name: props.title, value: props.value }],
          axisLabel: { formatter: `{value}${props.unit}` },
          pointer: {
            valueIndex: 0,
            itemStyle: {
              color: gradient,
            },
            style: { scale: [0.6, 0.6] },
          },
          axisLine: {
            lineStyle: {
              color: [
                [props.value / 100, gradient], // 根据值计算渐变
                [1, '#E0E0E0'], // 剩余的部分显示灰色
              ],
            },
          },
          details: {
            show: true,
            formatter: `{name}\n{value}${props.unit}`,
            position: 'center',
            style: { fontSize: 16, fontWeight: 'bold', textAlign: 'center' },
          },
          padding: [0, 0, 0, 0], // 上、右、下、左的边距均设置为0
        },
      ],
    }));

    // 监听 value 的变化，如果 value 变化，重新计算 gaugeOption
    watch(() => props.value, (newValue) => {
      console.log('New value for gauge:', newValue);
    });

    return {
      chartStyle,
      gaugeOption,
    };
  },
});
</script>
